/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Apr 14, 2012
 * Time: 4:14:41 PM
 * To change this template use File | Settings | File Templates.
 */
/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Mar 31, 2012
 * Time: 8:29:44 PM
 * To change this template use File | Settings | File Templates.
 */
/***************************/

  //global vars
	var form = $("#frmData");
	
    var sectionInfo =$("#sectionInfo");
    var instituteInfo =$("#instituteInfo");
    var section_id =$("#section_id");
    var categoryInfo=$("#categoryInfo");
    var toDate = $('#old_toDate');
    var fromDate = $('#fromDate');
    var toDateInfo = $('#old_toDateInfo');
    var fromDateInfo = $('#fromDateInfo');
    var uid = $("#id");


    var isEdit = false;

$(document).ready(function(){


    disableForm("frmData");
} );
//validation functions
function validateSection(){
		var instituteValue = $('#institute_id :selected').val();
		if(instituteValue==0){
			//section_id.addClass("errorField");
			instituteInfo.text("Please setect the employ Institute ");
			instituteInfo.addClass("errorField");
			return false;
		}else{
            instituteInfo.text("");
			instituteInfo.removeClass("errorField");
            return true;
        }
	}

function validateCategory(){
		var categoryValue = $('#categoy_id :selected').val();
		if(categoryValue==-1){
			//section_id.addClass("errorField");
			categoryInfo.text("Please setect the employ category ");
			categoryInfo.addClass("errorField");
			return false;
		}else{
            return true;
        }
	}
function validateToDate(){
		//if it's NOT valid
		if(toDate.val().length < 10){
			toDate.addClass("errorField");
			toDateInfo.text("Please Add Effective date");
			toDateInfo.addClass("errorField");
			return false;
		}
		//if it's valid
		else{
			toDate.removeClass("errorField");
			toDateInfo.text("");
			toDateInfo.removeClass("errorField");
			return true;
		}
	}
function validateFromDate(){
		//if it's NOT valid
		if(fromDate.val().length < 10){
			fromDate.addClass("errorField");
			fromDateInfo.text("Please Add Effective date");
			fromDateInfo.addClass("errorField");
			return false;
		}
		//if it's valid
		else{
			fromDate.removeClass("errorField");
			fromDateInfo.text("");
			fromDateInfo.removeClass("errorField");
			return true;
		}
	}



  function clearValidate(){
        toDateInfo.removeClass("errorField");
        toDateInfo.text("");
        fromDateInfo.removeClass("errorField");
        fromDateInfo.text("");
        categoryInfo.removeClass("errorField");
        categoryInfo.text("");
        sectionInfo.text("");
        sectionInfo.removeClass("errorField");
        instituteInfo.removeClass("errorField");
		instituteInfo.text("");
  }

//////page data  ////
var isNew = false;

//////////// data Grid /////////
var mygrid;
var timeoutHnd;
var flAuto = false;
function gridGenerator() {
    mygrid = new dhtmlXGridObject('gridbox');
    mygrid.setImagePath("images/dhtmlx/imgs/");
    mygrid.setHeader("ID,Full Name,Name with Initial,NIC,Institute,Section,Email,Status,sta,ins,sec,cat");
    mygrid.setInitWidths("30,200,200,100,200,200,200,75,50,50,50,50");
    mygrid.setColAlign("left,left,left,left,left,left,left,left,left,left,left,left");
    mygrid.setColSorting("server,server,server,server,server,na,na,na,na,na,na,na");
    mygrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro,ro,ro,ro,ro");
    if (mygrid.setColspan){
       mygrid.attachEvent("onBeforeSorting", customColumnSort);
    }
    mygrid.setSkin("dhx_skyblue");
    mygrid.enablePaging(true,10, 10, "pagingArea", true, "infoArea");
    mygrid.setPagingSkin("toolbar", "dhx_skyblue");
    mygrid.init();
    mygrid.attachEvent("onBeforePageChanged", function() {
        if (!this.getRowsNum()){
            return false;
        }
        return true;
    });
    mygrid.sortField_old = mygrid.sortField;
    mygrid.sortField = function() {
        mygrid.setColSorting("str,str,str,str,str,str,str,str,str,str,str,str");
        if (customColumnSort(arguments[0]))
        mygrid.sortField_old.apply(this, arguments);
    }
    mygrid.setColumnHidden(8,true);
    mygrid.setColumnHidden(9,true);
    mygrid.setColumnHidden(10,true);
    mygrid.setColumnHidden(11,true);
    mygrid.sortRows = function(col, type, order) {}
    mygrid.attachEvent("onRowSelect",doOnRowSelected);
    mygrid.attachEvent("onXLE", showLoading);
    mygrid.attachEvent("onXLS", function() {
        showLoading(true)
    });
    mygrid.loadXML("?employee/gridEmploy&un=" + Date.parse(new Date()),function(){
      var myToolbar=mygrid.aToolBar;
        //myToolbar.setSkin("dhx_black");

   });
}

function showLoading(fl) {
    var span = document.getElementById("recfound");
    if (!span)
        return;
    if (!mygrid._serialise) {
        span.innerHTML = "<i>Loading... available in Professional Edition of dhtmlxGrid</i>";
        return;
    }
    span.style.color = "red";
    if (fl === true)
    span.innerHTML = "loading...";
    else
    span.innerHTML = "";
}

function doSearch(ev) {
    if (!flAuto)
    return;
    var elem = ev.target || ev.srcElement;
    if (timeoutHnd)
    clearTimeout(timeoutHnd);
    timeoutHnd = setTimeout(reloadGrid, 500);
}
function reloadGrid() {
    var searchCriteriaInstitute = document.getElementById("searchCriteria.institute").value;
    var searchCriteriaName = document.getElementById("searchCriteria.name").value;
    var searchCriteriaNic = document.getElementById("searchCriteria.nic").value;
    showLoading(true);
    mygrid.clearAndLoad("?employee/gridEmploy&name=" + searchCriteriaName + "&institute=" + searchCriteriaInstitute + "&nic="+searchCriteriaNic+"&orderBy=" + window.s_col + "&direction=" + window.a_direction);
    if (window.a_direction)
    mygrid.setSortImgState(true, window.s_col, window.a_direction);
}
function enableAutosubmit(state) {
    flAuto = state;
    document.getElementById("submitButton").disabled = state;
}

function customColumnSort(ind) {
    if (ind == 1) {
        window.s_col = 0;
        // alert("Table can't be sorted by this column.");
       //if (window.s_col)
        mygrid.setSortImgState(true, 1, window.a_direction);
       // return false;
    }else{
          window.s_col = ind;
    }
    // window.s_col = ind;
    var a_state = mygrid.getSortingState();

    window.a_direction = ((a_state[1] == "des") ? "asc": "des");
    reloadGrid();
    return true;
}

function doOnRowSelected(rowID,celInd){
    clearForm("frmData");
    clearValidate();
    disableForm("frmData");
    $("#initName").html("" ) ;
    $("#initName").html("Employ Name : "+mygrid.cells(rowID,1).getValue()) ;
     document.getElementById("old_institute_id").value  =mygrid.cells(rowID,4).getValue() ;
     document.getElementById("old_section_id").value  = mygrid.cells(rowID,5).getValue() ;
     document.getElementById("old_category_id").value  = mygrid.cells(rowID,11).getValue() ;
     document.getElementById("empId").value  = rowID;

    var params =encodeURIComponent("employId") + "="+rowID+"&insId="+mygrid.cells(rowID,9).getValue()+"&secId="+mygrid.cells(rowID,10).getValue();
    ajaxPost("?employee/getEmpIns", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
            $("#tableHtml").html("" ) ;
            $("#tableHtml").html(response.tableHtml) ;
            document.getElementById("old_fromDate").value  = response.fromDate.fields.from_date;
            document.getElementById("id").value  = response.fromDate.fields.id;
            handleDefaultButtons("gridclick");
		});
    $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
}

function clearButton(){   
    $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
    $("#tableHtml").html("" ) ;
    initialize();
}
function initialize(fnAfterInit) {
    $("#initName").html("" ) ;
    $("#tableHtml").html("" ) ;
    clearForm("frmData");
    clearValidate();
    disableForm("frmData");
    handleDefaultButtons("load");

}
function edit(){
    enableForm("frmData");
    handleDefaultButtons("edit");
    disableElement("old_institute_id");
    disableElement("old_section_id");
    disableElement("old_category_id");
    disableElement("old_fromDate");
  
    isEdit=true;
}
function cancel(){
    initialize();
    $("#tableHtml").html("" ) ;
    $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
}
function save(){
                if(validateSection() && validateCategory()&& validateToDate() && validateFromDate()) {
                var params = serializeForm("frmData") ;
                ajaxPost("?employee/addEmpMap", params, function(data) {
			var response ;
            try
                {
                    response =JSON.parse(data);
                     $("#messagePanel").removeClass();
                     $("#messagePanel").addClass(response.type);
                     $("#messagePanel").html(response.message ) ;
                    if (response.status==false) {
				return;
			}
                }
                catch(err)
                {

                    $("#messagePanel").removeClass();
                     $("#messagePanel").addClass('error');
                     $("#messagePanel").html(data ) ;
                }


            reloadGrid();
			initialize();
		});
    }
		else
			return false;

    handleDefaultButtons("save");



}

function del(){
    var isDelete=confirm("Confirm to Delete '"+ document.getElementById("fullName").value + "'  User !");
    if(isDelete ) {
        var params = serializeForm("frmData") ;
        ajaxPost("?employee/delete", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
            $("#messagePanel").removeClass();
            $("#messagePanel").addClass(response.type);
            $("#messagePanel").html(response.message ) ;
            reloadGrid();
			initialize();
		});
    }
		else
			return false;
    handleDefaultButtons("delete");
}
function doChangeSection(para){
    $("#section_id").find('option').remove().end();
    var params =encodeURIComponent("instituteId") + "="+document.getElementById("institute_id").value;
    ajaxPost("?employee/getSectionList", params, function(data) {
			var response =data;
			if (response.status==false) {
				return;
			}
                $('#section_id').append(response);
        $("#section_id").val( para).attr('selected',true);
    });
}
function closePage(){
    window.location.href="?home";
}

function onLoad(){
     initialize();
     gridGenerator();
     enforcePrivileges();
    _fromDate = new dhtmlXCalendarObject(["fromDate"]);
    _fromDate.hideTime();
     _toDate = new dhtmlXCalendarObject(["old_toDate"]);
    _toDate.hideTime();
}

onLoad();